package cn.scw.project.facility.service.impl;

import cn.scw.common.utils.bean.BeanUtils;
import cn.scw.common.utils.pay.*;
import cn.scw.project.facility.domain.FacPrintOrder;
import cn.scw.project.facility.domain.netework.bean.WxSharingOrderRequest;
import cn.scw.project.facility.domain.netework.bean.WxSharingOrderResp;
import cn.scw.project.facility.domain.vo.WxSharingReceiversVO;
import cn.scw.project.facility.service.IWxPayService;
import cn.scw.project.separate.domain.SeparateVo;
import cn.scw.project.separate.service.SaRecordService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class WxPayServiceImpl implements IWxPayService {

    @Resource
    private SaRecordService saRecordService;

    @Override
    public WxSharingOrderResp oncePaySharing(FacPrintOrder order) throws Exception {
        WxSharingOrderResp resp = null;
        WxSharingOrderRequest wxSharingOrderRequest = new WxSharingOrderRequest();
        wxSharingOrderRequest.setAppid(ConfigUtil.APP_ID);
        wxSharingOrderRequest.setMch_id(ConfigUtil.MCH_ID);
        wxSharingOrderRequest.setTransaction_id(order.getTransactionId());//订单号
        // 生成随机字符串
        wxSharingOrderRequest.setNonce_str(ConfigUtil.makeNonStr());
        wxSharingOrderRequest.setOut_order_no(order.getNumber());//分账单号

        //添加分账记录、获取分账账户
        List<WxSharingReceiversVO> list = inserFenZhangAndGetReceviers(order);
        if(CollectionUtils.isEmpty(list)){
             resp = new WxSharingOrderResp();
            resp.setReturn_code("FAIL");
            resp.setReturn_msg("没有分账记录");
            return resp;
        }
        wxSharingOrderRequest.setReceivers(JSON.toJSONString(list));

        BeanMap beanMap = BeanMap.create(wxSharingOrderRequest);
        wxSharingOrderRequest.setSign(WxUtils.makeSign(beanMap,ConfigUtil.API_KEY,"SHA256"));
        String xmlStr = WxUtils.truncateDataToXML(WxSharingOrderRequest.class, wxSharingOrderRequest).replace("&quot;","\"");
        System.out.println("分账请求参数："+xmlStr);
        String result = WxCertHttpUtil.postData(ConfigUtil.PROFIT_SHARING_URL,xmlStr,ConfigUtil.MCH_ID,"");
        System.out.println("分账请求返回结果："+result);
        Object obj = WxUtils.truncateDataFromXML(WxSharingOrderResp.class, result);
        resp = new WxSharingOrderResp();
        BeanUtils.copyProperties(obj,resp);
        return resp;
    }

    @Override
    public WxSharingOrderResp paySharingQuery(FacPrintOrder order) throws Exception {
        WxSharingOrderRequest wxSharingOrderRequest = new WxSharingOrderRequest();
        wxSharingOrderRequest.setMch_id(ConfigUtil.MCH_ID);
        wxSharingOrderRequest.setTransaction_id(order.getNumber());//订单号
        // 生成随机字符串
        wxSharingOrderRequest.setNonce_str(ConfigUtil.makeNonStr());
        wxSharingOrderRequest.setOut_order_no(order.getNumber());//分账单号

        BeanMap beanMap = BeanMap.create(wxSharingOrderRequest);
        wxSharingOrderRequest.setSign(WxUtils.makeSign(beanMap,ConfigUtil.API_KEY,"SHA256"));
        String xmlStr = WxUtils.truncateDataToXML(WxSharingOrderRequest.class, wxSharingOrderRequest).replace("&quot;","\"");
//        String url = "https://api.mch.weixin.qq.com/secapi/pay/profitsharing";
        String result = WxCertHttpUtil.postData(ConfigUtil.PROFIT_SHARING_QUERY_URL,xmlStr);
        Object obj = WxUtils.truncateDataFromXML(WxSharingOrderResp.class, result);
        WxSharingOrderResp resp = new WxSharingOrderResp();
        BeanUtils.copyProperties(obj,resp);
        return resp;
    }

    private List<WxSharingReceiversVO> inserFenZhangAndGetReceviers(FacPrintOrder order){
        List<WxSharingReceiversVO> list = Lists.newArrayList();
        List<SeparateVo> fenzhangList = saRecordService.queryUserRecord(order.getId());
        for(SeparateVo fenzhang : fenzhangList){
            WxSharingReceiversVO receiversVO = new WxSharingReceiversVO();

            if(fenzhang.getOpenId() != null ){
                receiversVO.setAccount(fenzhang.getOpenId());
                receiversVO.setType("PERSONAL_OPENID");//MERCHANT_ID或者个人为PERSONAL_OPENID
                receiversVO.setDescription("分到个人");
            }else if(fenzhang.getMercNo() != null ){
                receiversVO.setAccount(fenzhang.getMercNo());
                receiversVO.setType("MERCHANT_ID");//MERCHANT_ID或者个人为PERSONAL_OPENID
                receiversVO.setDescription("分到商户");
            }else{
                continue;//如果openId和mercNo都为空，也不能进行分账
            }
            receiversVO.setAmount(fenzhang.getGetMoney().multiply(BigDecimal.TEN.multiply(BigDecimal.TEN)).intValue());

            list.add(receiversVO);
        }
        return list;
    }

    @Override
    public WxSharingOrderResp multiPaySharing(WxSharingOrderRequest data) throws Exception {
        return null;
    }
}
